from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from django.core import serializers
import logging

logger = logging.getLogger('log')

from ..models import ptTestProject
from ..serverEvCfg import httpResponseSignal


@csrf_exempt  # 此接口允许跨域访问
@api_view(['POST'])
def addProject(request):
    '''
    添加项目
    :param request:
    :return:
    '''
    print(request.body)
    data = eval(json.loads(request.body)["data"])
    print(data)
    try: # 成功
        if (data["name"] != None and data["runningAddress"] != None):
            project = ptTestProject(pj_img=data["imageUrl"],
                                    pj_name=data["name"],
                                    pj_running_address=data["runningAddress"],
                                    remark=data["describe"],
                                    configure_address=data["configure_address"],
                                    otherconfigure="暂无"
                                    )
            project.save()
            response = httpResponseSignal.httpResponseSignal().getSuccess()
            return JsonResponse(response)
        else: # 错误 缺少必要参数
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"]= "缺少必要参数,请检查"
            return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr
        return JsonResponse(response)

@csrf_exempt
@api_view(['GET'])
def getProject(request): # 获取所有项目的详细内容
    '''
    获取所有项目
    :return:
    '''
    try:
        allProjectData = ptTestProject.objects.all() # 获取QuerySet对象
        data = json.loads(serializers.serialize("json",allProjectData))
        print(allProjectData)
        print(data)

        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"]=data
        return  JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr
        return JsonResponse(response)


